<template>
  <view class="priority-selector">
    <u-picker
      :show="showPicker"
      :columns="priorityColumns"
      @confirm="onConfirm"
      @cancel="onCancel"
      title="选择优先级"
    />
    <u-input
      v-model="displayValue"
      :placeholder="placeholder"
      readonly
      @click="openPicker"
      class="priority-input"
    />
  </view>
</template>

<script setup>
import { ref, computed, watch } from 'vue'

// Props
const props = defineProps({
  modelValue: {
    type: Number,
    default: 1
  },
  placeholder: {
    type: String,
    default: '请选择优先级'
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'change'])

// 响应式数据
const showPicker = ref(false)
const selectedValue = ref(props.modelValue)

// 优先级选项
const priorityOptions = [
  { label: '低', value: 1 },
  { label: '中', value: 2 },
  { label: '高', value: 3 },
  { label: '紧急', value: 4 }
]

// 计算属性
const priorityColumns = computed(() => {
  return [priorityOptions]
})

const displayValue = computed(() => {
  const option = priorityOptions.find(item => item.value === selectedValue.value)
  return option ? option.label : ''
})

// 监听props变化
watch(() => props.modelValue, (newValue) => {
  selectedValue.value = newValue
})

// 方法
const openPicker = () => {
  showPicker.value = true
}

const onConfirm = (event) => {
  const selectedOption = event.value[0]
  selectedValue.value = selectedOption.value
  emit('update:modelValue', selectedOption.value)
  emit('change', selectedOption)
  showPicker.value = false
}

const onCancel = () => {
  showPicker.value = false
}
</script>

<style lang="scss" scoped>
.priority-selector {
  .priority-input {
    width: 100%;
  }
}
</style>
